<template>
  <div ref="swiper" class="wid-hei-inherit">
    <div class="swiper swiper-container">
      <div class="swiper-wrapper">
        <div
          v-for="(page, index) in pages"
          :key="page.id"
          :id="'page-' + (index+1)"
          :style="siteStyles_(page, index)"
          :class="['page', 'swiper-slide', {'swiper-no-swiping': noSwipings[index]}]"
        >
          <!-- <div :style="page.styles"> -->
            <group-component :item="page" :pageId="index+1" :style="page.styles" class="swiper-page"></group-component>
          <!-- </div> -->
        </div>
      </div>
      <div class="swiper-pagination"></div>
    </div>
    <img v-if="displaySwiperArrow" :src="swiperArrowUrl" class="ani-swipe" :style="arrowWidHei">
    <div v-if="siteAttrs.isDisplayDebuggerText" class="version"> {{ version }} </div>
  </div>
</template>
<script>
import { EventBus } from '@/store/index'
import { PAGE_MODE_MAP } from '@/common/const'
import { COMPONENT_TYPES } from '@/common/const-wb'
import { EVENT_HOVER_TYPES } from '@/common/events'
import { defineAsyncComponent } from 'vue'
import { commonUtils } from '@/components/utils/common-utils'
import { pageTemplate } from '@/components/utils/page-template'
import { wbBase } from '@/components/utils/wbBase'
import { pageAnimate } from '@/others/pages/js/page-animate'
import { pageLoading } from '@/others/pages/js/page-loading'
import { pageCommon } from '@/others/pages/js/page-common'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { reactive, ref } from 'vue'
import { getPxOVwByValue } from '@/store/utils'


const components = {
  GroupComponent: defineAsyncComponent(() => import('@/components/group-component.vue')),
};
export default {
  mixins: [commonUtils, pageTemplate, pageAnimate, pageLoading, pageCommon, wbBase],
  setup () {
    const state =  reactive({
      version: '版本v3.5',
      noSwipings: [],
      currentPage: null,
      swiper_: null,
    })
    const state_ = {
      isPostInit: false,
      pageHaveForms: {},
    }
    _.merge(state, state_)
    return state
  },
  created(){
    _.forEach(this.pages, () => {
      this.noSwipings.push(false);
    })
    if(this.siteAttrs.noSwipings){
      let noSwipings = this.siteAttrs.noSwipings.split(",");
      _.forEach(noSwipings, (pageId) => {
        this.noSwipings[pageId-1] = true;
      })
    }
    EventBus.$off("displayDebuggerInfo", this.onDisplayDebuggerInfo)
    EventBus.$on("displayDebuggerInfo", this.onDisplayDebuggerInfo)
    // import('swiper' /* webpackChunkName: "swiper" */).then((module) => {
    //   let Swiper = module.default
    //   this.initSwiper(Swiper)
    // })
    // if(!window.Swiper){
    //   this.dynamicsLoadScript(this.env.baseUrl + 'js/swiper-bundle.min.js?v=7', 'Swiper', this.initSwiper);
    // }

    _.forEach(this.pages, (page, pageIndex) => {
      this.setPageHaveForm(page.components, pageIndex);
    })
    EventBus.$off("swiper", this.showLoading)
    EventBus.$on("swiper", this.showLoading)
    EventBus.$off("swiperNoneLoading", this.onSlideTo)
    EventBus.$on("swiperNoneLoading", this.onSlideTo)
  },
  components,
  computed: {
    displaySwiperArrow(){
      if(this.siteAttrs.turnPageMode == PAGE_MODE_MAP.top_down && this.pages.length > 1
        && !this.siteAttrs.isNoSwiping && this.statePopId <= 0 && this.pageIndex != this.pages.length-1 && !this.getCurrentPageIsHaveJumpEvent
        && !this.noSwipings[this.pageIndex]){
        return true;
      }else{
        return false;
      }
    },
    getCurrentPageIsHaveJumpEvent(){
      let page = this.pages[this.pageIndex];
      let isEvent =  this.getEventByType(page, EVENT_HOVER_TYPES.anchor.type);
      return isEvent;
    },
    swiperArrowUrl(){
      let url = ''
      if(this.siteAttrs.swiperHintUrl && this.siteAttrs.swiperHintUrl.length > 0){
        url = this.siteAttrs.swiperHintUrl.split(',')[0];
      }else{
        url = `${this.env.baseUrl}images/web-swipe-tip.png`;
      }
      return url;
    },
    arrowWidHei(){
      let reallyWidth = MOBILE_WID_HEI.clientWidth*MOBILE_WID_HEI.adaptiveScale;
      if(this.siteAttrs.swiperHintUrl && this.siteAttrs.swiperHintUrl.length > 0){
        if(MOBILE_WID_HEI.adaptiveScale <= 1 && !this.siteInfo.md.isMobile) {
          reallyWidth = MOBILE_WID_HEI.clientWidth
        }
        const arr = this.siteAttrs.swiperHintUrl.split(',');
        const width = arr[1] ? arr[1] : 300;
        const height = arr[2] ? arr[2] : 105;
        const bottom = arr[3] ? arr[3] : 2;
        return {
          width: getPxOVwByValue(width),
          height: getPxOVwByValue(height),
          left: getPxOVwByValue((reallyWidth-width)/2),
          bottom: bottom + "%",
        }
      }else{
        return {
          width: getPxOVwByValue(48),
          height: getPxOVwByValue(36),
          left: getPxOVwByValue((reallyWidth-48)/2),
        };
      }
    },
    getIsNoSwiping(){
      let isNoSwipings = false;
      if(this.siteAttrs.noSwipings){
        const noSwipings = this.siteAttrs.noSwipings.split(',');
        if(noSwipings.length > 0){
          isNoSwipings = true;
        }
      }
      return isNoSwipings;
    },
    swiperOption() {
      let this_ = this;
      return {
        updateOnWindowResize: true,
        preloadImages: false,//默认为true，Swiper会强制加载所有图片。
        runCallbacksOnInit: true,//slideChangeTransitionStart
        watchOverflow: true,//当没有足够的slide切换时，例如只有1个slide，swiper会失效且隐藏导航等。默认不开启这个功能。
        preventInteractionOnTransition: true,
        direction: this.siteAttrs.turnPageMode == PAGE_MODE_MAP.top_down ? "vertical" : "horizontal",
        speed: this.siteAttrs.turnPageTime * 1000,//切换速度，即slider自动滑动开始到结束的时间（单位ms），也是触摸滑动时释放至贴合的时间。
        width: MOBILE_WID_HEI.clientWidth,
        height: MOBILE_WID_HEI.clientHeight,
        mousewheel: !this.siteAttrs.isTurnPage, //禁止滑动翻页，
        autoplay: this.siteAttrs.autoTurnPage,
        effect: this.siteAttrs.effect ? this.siteAttrs.effect : 'slideInUp',//slideInUp
        // fadeEffect: {
        //   crossFade: true,
        // },
        //slide的切换效果，默认为"slide"（位移切换），可设置为'slide'（普通切换、默认）,"fade"（淡入）"cube"（方块）"coverflow"（3d流）"flip"（3d翻转）。
        on: {
          transitionStart: function() {
            const pageIndex = this.activeIndex;
            const pageId = pageIndex + 1;
            if(this_.pagePageId != pageId){
              this_.$store.commit('updatePageIndex', { pageIndex });
              EventBus.$emit('pauseVideo', { pageId });
              EventBus.$emit('playOrPauseAudio', { isPlay: false });
            }
            this_.showLoading({ pageId: pageId});
          },
          slideChangeTransitionStart: function() {
            this_.showPageById(this.activeIndex);
          },
          // transitionEnd: function(){
          // },
          // slideChangeTransitionEnd: function() {
          //   this_.clearAnimates(this.activeIndex-1);
          // },
        },
        pagination: {
          el: process.env.NODE_ENV === 'production' ? "" : ".swiper-pagination",
          clickable: process.env.NODE_ENV === 'production' ? false : true,
        }
      };
    },
    swiper(){
      return this.swiper_
    }
  },
  mounted(){
    if(window.Swiper){
      this.initSwiper(window.Swiper);
      this.clearFirstAnimates(this.pageIndex);
    }else{
      this.loadSwiperCb = window.setInterval(() => {
        if(window.Swiper){
          window.clearInterval(this.loadSwiperCb);
          this.initSwiper(window.Swiper);
          this.clearFirstAnimates(this.pageIndex);
        }
      }, this.siteInfo.reloadTime);
    }
    // window.setTimeout(function(){document.querySelectorAll('input').forEach((item,k)=>{if (k>0){ item.onblur=function(){document.querySelector('.swiper-container').setAttribute('style','height:100vh');document.querySelector('.swiper-page').setAttribute('style','height:100vh');document.querySelector('input').focus();document.querySelector('input').blur();}}})},2000)
  },
  methods: {
    getPageDisplay(pageId){
      if(pageId == (this.pageIndex+1)){
        return true
      }else{
        return false
      }
    },
    onDisplayDebuggerInfo({text}){
      this.version = text;
    },
    showLoading( { pageId } ) {
      const pageIndex = pageId - 1;

      // this.$store.commit('updatePageIndex', { pageIndex });

      this.currentPage = this.pages[pageIndex];
      this.pagePageId = pageId;

      this.pageInitEvents()

      if(!this.isPostInit){
        this.eventPostAddLoading({});
        this.isPostInit = true;
      }

      this.slideTo({ pageId });

      this.$nextTick(() => {
        const pageId_ = 'page-' + pageId;
        const currentPageDom = document.getElementById(pageId_);
        this.initPlayAllAnimates(currentPageDom);
      })

      //底部菜单
      EventBus.$emit("slideTab", { slideIndex: pageIndex });
    },
    showPageById(pageIndex){
      this.refreshForm(pageIndex);
    },
    refreshForm(pageIndex){
      if(this.pageHaveForms[pageIndex]){
        this.isFixIosForm();
      }
    },
    setPageHaveForm(components, pageIndex){
      _.forEach(components, (componentData) => {
        if(componentData.events.submit){
          this.pageHaveForms[pageIndex] = true;
        }else if(componentData.components && componentData.components.length > 0){
          this.setPageHaveForm(componentData.components, pageIndex);
        }
      })
    },
    getEventByType(page, eventType){
      for(let i = 0, len = page.components.length; i < len; i++){
        let componentData = page.components[i];
        let events = componentData.events;
        if(events[eventType]){
          return true;
        }else if(componentData.components && componentData.components.length > 0){
          return this.getEventByType(componentData, eventType)
        }
      }
      return false
    },
    initSwiper(Swiper){
      let swiperDom = this.$refs.swiper;

      this.intervalCb = setInterval(() => {
        if(swiperDom){
          let swiperContainer = swiperDom.querySelector(".swiper-container");
          let pages = swiperDom.querySelectorAll(".swiper-page");
          if(pages.length > 0){
            window.clearInterval(this.intervalCb);
            this.swiperOption.noSwiping = this.getIsNoSwiping;
            this.swiper_ = new Swiper(swiperContainer, this.swiperOption);

            if(this.isMountLoading){
              if(this.pages && this.pageIndex >= 0 && this.pages[this.pageIndex]) {
                this.showLoading({ pageId: this.pageIndex+1 });
              }
            }
          }
        }
      }, this.siteInfo.reloadTime);
    },
    onSlideTo({pageId}){
      this.slideTo({pageId})
    },
    slideTo({pageId}) {
      let slideIndex = parseInt(pageId) - 1
      if(this.swiper){
        this.swiper.slideTo(slideIndex, 100, false)
      }
    },
    siteStyles_(page, index) {
      let styles_ = _.cloneDeep(this.siteStyles)
      styles_.width = page.styles.width;
      styles_.height = page.styles.height;
      if(this.noSwipings[index]){
        styles_['touch-action'] = 'none';
      }else{
        styles_['touch-action'] = 'default';
      }
      return styles_;
    },
    getSiteBgUrl(){
      let url = this.siteStyles.backgroundImage
      let url_ = url.match(/\((\S*)\)/)
      return url_[1] ? url_[1] : ''
    },
    getPageBgUrl(page){
      let url = page.styles.backgroundImage
      let url_ = url.match(/\((\S*)\)/)
      return url_[1] ? url_[1] : ''
    },
    pageStyles_(page) {
      let styles_ = _.cloneDeep(page.styles)
      return styles_;
    },
  },
  beforeUnmount(){
    EventBus.$off("swiper", this.showLoading)
    EventBus.$off("swiperNoneLoading", this.onSlideTo)
    EventBus.$off("displayDebuggerInfo", this.onDisplayDebuggerInfo)
  }
};
</script>

<style scoped>
.swiper-pagination {
  position: fixed;
  /* opacity: 0.01; */
}
</style>

